﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NSX07
{
    public partial class products : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ProductDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {

            // Retrieve output parameter values returned from calling the "ProductsTableAdapter.GetProductsByCategoryId" 
            // method invoked by the ObjectDataSource control
            int productCount = (int)e.OutputParameters["CategoryProductCount"];
            string categoryName = (string)e.OutputParameters["CategoryName"];

            // Retrieve pageIndex and categoryId from querystring, pageSize pulled from ObjectDataSource parameter
            int pageIndex = Convert.ToInt32(Request.QueryString["pageIndex"]);
            int categoryId = Convert.ToInt32(Request.QueryString["id"]);
            int pageSize = Int32.Parse(ProductDataSource.SelectParameters["NumRows"].DefaultValue);

            // Update various page elements with data values
            UpdateTitles(categoryName);
            UpdatePagerLocation(pageIndex, pageSize, productCount);
            UpdateNextPrevLinks(categoryId, pageIndex, pageSize, productCount);
        }
        void UpdateTitles(string title)
        {

            ProductHeader.Text = title;
            Page.Title = "Products: " + title;
        }

        void UpdatePagerLocation(int pageIndex, int pageSize, int productCount)
        {

            int currentStartRow = (pageIndex * pageSize) + 1;
            int currentEndRow = (pageIndex * pageSize) + pageSize;

            if (currentEndRow > productCount)
                currentEndRow = productCount;

            PagerLocation.Text = currentStartRow + "-" + currentEndRow + " of " + productCount + " products";
        }

        void UpdateNextPrevLinks(int categoryId, int pageIndex, int pageSize, int productCount)
        {

            string navigationFormat = "products.aspx?id={0}&pageIndex={1}";

            PreviousPageNav.HRef = String.Format(navigationFormat, categoryId, pageIndex - 1);
            PreviousPageNav.Visible = (pageIndex > 0) ? true : false;

            NextPageNav.HRef = String.Format(navigationFormat, categoryId, pageIndex + 1);
            NextPageNav.Visible = (pageIndex + 1) * pageSize < productCount ? true : false;
        }
    }
}
